package com.leeson.portal.core.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.RequestDispatcher;
//import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;

import com.leeson.portal.core.model.Config;
import com.leeson.portal.core.model.OnlineMap;
import com.leeson.portal.core.service.InterfaceControl;
import com.leeson.portal.core.utils.SpringContextHelper;
import com.leeson.portal.manage.domain.Account;
import com.leeson.portal.manage.domain.LinkRecord;
import com.leeson.portal.manage.domain.LogRecord;
import com.leeson.portal.manage.service.AccountService;
import com.leeson.portal.manage.service.LinkRecordService;
import com.leeson.portal.manage.service.LogRecordService;

/**
 * 退出
 * 
 * @author LeeSon QQ:25901875
 */
public class LoginOut extends HttpServlet {

	private static final long serialVersionUID = 5118888119558797794L;
	Logger logger = Logger.getLogger(LoginOut.class);
	OnlineMap onlineMap=OnlineMap.getInstance();

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setAttribute("msg", "请不要重复刷新！");
		request.getRequestDispatcher("/WEB-INF/jsp/indexAction/index.jsp").forward(request, response);

	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();
		Config cfg = Config.getInstance();
		
		try {
			
			String ip=request.getRemoteAddr();
			String username = (String) session.getAttribute("username");
			String password = (String) session.getAttribute("password");
			
			if(cfg.getAuth_interface().equals("0")){
				username=cfg.getBas_user();
				password=cfg.getBas_pwd();
			}

			
			if(cfg.getDebug().equals("1")){
				logger.info("请求下线    用户：" + username + " 密码:" + password + " IP地址:"
						+ ip);
			}
			
			
			boolean state=onlineMap.getOnlineUserMap().containsKey(ip);
			if (!state) {
				session.removeAttribute("username");
				session.removeAttribute("password");
				session.removeAttribute("ip");
				request.setAttribute("msg", "用户信息丢失，请重新登录后再退出！");
				request.getRequestDispatcher("/WEB-INF/jsp/indexAction/index.jsp").forward(request,
						response);
				return;
			} else {
				Boolean info = InterfaceControl.Method("PORTAL_LOGINOUT",
						username, password, ip);

				if (info == true) {
					
					//改变连接日志，修改计费记录
					if(cfg.getAuth_interface().equals("1")){
						doLinkRecord(request, ip);
					}
					
					
					//修改在线列表
					onlineMap.getOnlineUserMap().remove(ip);
					
					//新建下线日志
					doLogRecord(request, ip, username);
					
					
					session.removeAttribute("username");
					session.removeAttribute("password");
					session.removeAttribute("ip");
					request.setAttribute("msg", "用户退出登录！");
					request.getRequestDispatcher("/WEB-INF/jsp/indexAction/index.jsp").forward(request,
							response);
				} else {

					request.setAttribute("msg", "下线失败,请稍后再试！！");
					RequestDispatcher qr = request
							.getRequestDispatcher("/WEB-INF/jsp/indexAction/index.jsp");
					qr.forward(request, response);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			request.setAttribute("msg", "异常错误，请联系管理员！！");
			request.getRequestDispatcher("/WEB-INF/jsp/indexAction/index.jsp").forward(request,
					response);
		}

	}

	/**
	 * 下线日志
	 * @param request
	 * @param ip
	 * @param username
	 */
	private void doLogRecord(HttpServletRequest request, String ip,
			String username) {
//		ServletContext sc=request.getServletContext();
//		ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
		ApplicationContext ac = SpringContextHelper.getApplicationContext();
		LogRecord logRecord=new LogRecord();
		Date nowDate=new Date();
		logRecord.setInfo("IP:"+ip+",用户："+username+",主动下线成功!");
		logRecord.setRec_date(nowDate);
		LogRecordService logRecordService=(LogRecordService) ac.getBean("logRecordServiceImpl");
		logRecordService.save(logRecord);
	}
	/**
	 * 连接日志
	 * @param request
	 * @param ip
	 * @param username
	 */
	private void doLinkRecord(HttpServletRequest request, String ip) {
//		ServletContext sc=request.getServletContext();
//		ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
		ApplicationContext ac = SpringContextHelper.getApplicationContext();
		
		LinkRecordService linkRecordService=(LinkRecordService) ac.getBean("linkRecordServiceImpl");
		AccountService accountService=(AccountService) ac.getBean("accountServiceImpl");
		String[] loginInfo=onlineMap.getOnlineUserMap().get(ip);
		
		Long userId=Long.parseLong(loginInfo[1]);
		Long recordId=Long.parseLong(loginInfo[2]);
		Date now=new Date();
		
		LinkRecord linkRecord=linkRecordService.getById(recordId);
		linkRecord.setEndDate(now);
		Long costTime=now.getTime()-linkRecord.getStartDate().getTime();
		linkRecord.setTime(costTime);
		linkRecordService.update(linkRecord);
		
		Account account=accountService.getById(userId);
		String state=account.getState();
		Long haveTime=account.getTime();
		Long newHaveTime=haveTime-costTime;
		if(state.equals(String.valueOf(2))){
			if(newHaveTime<=0){
				account.setState(String.valueOf(0));
			}
			account.setTime(newHaveTime);
			accountService.update(account);
		}
		
	}

}
